package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;


    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    /**
     * 分页条件查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public Result queryPage(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        List<Setmeal> list = setmealDao.findByCondition(queryPageBean.getQueryString());

        Result result;

        if (list.isEmpty()) {
            result = new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        } else {
            result = new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, new PageInfo<>(list));
        }

        return result;
    }


    /**
     * 添加套餐
     *
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @Override
    public Result addSetmeal(Setmeal setmeal, Integer[] checkgroupIds) {

        //添加套餐完成时 通过套餐id添加与检查组的关系
        Integer count;
        count = setmealDao.saveSetmeal(setmeal);
        if (count == 0)
            throw new RuntimeException(MessageConstant.ADD_SETMEAL_FAIL);

        for (Integer checkgroupId : checkgroupIds) {

            //取到每一个检查组ID循环添加到中间表中
            count = setmealDao.setSetmealAndCheckGroup(setmeal.getId(), checkgroupId);

            if (count == 0)
                throw new RuntimeException(MessageConstant.ADD_SETMEAL_FAIL);
        }


        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 编辑套餐
     *
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @Override
    public Result editSetmeal(Setmeal setmeal, Integer[] checkgroupIds) {

        //修改套餐之后,先删除中间表的关联关系,再添加新的关系
        Integer count;
        count = setmealDao.editSetmeal(setmeal);
        if (count == 0)
            throw new RuntimeException("修改套餐失败");

        //删除中间关系
        setmealDao.deleteAssociation(setmeal.getId());


        for (Integer checkgroupId : checkgroupIds) {

            //取到每一个检查组ID循环添加到中间表中
            count = setmealDao.setSetmealAndCheckGroup(setmeal.getId(), checkgroupId);

            if (count == 0)
                throw new RuntimeException(MessageConstant.ADD_SETMEAL_FAIL);
        }

        return new Result(true, "编辑成功");
    }

    @Override
    public Result deleteSetmeal(Integer setmealId) {
        //先删除中间表的关系 在删除套餐
        setmealDao.deleteAssociation(setmealId);

        //删除套餐
        Integer count = setmealDao.deleteSetmeal(setmealId);
        if (count == 0)
            throw new RuntimeException(MessageConstant.DELETE_SETMEAL_FAIL);

        return new Result(true, MessageConstant.DELETE_SETMEAL_SUCCESS);
    }

    /**
     * 查询所有套餐
     *
     * @return
     */
    @Override
    public Result findAll() {
        List<Setmeal> setmealList = setmealDao.findAll();

        for (Setmeal setmeal : setmealList) {

            try {
                createSetMealDetailHtml(setmeal.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        if (setmealList == null || setmealList.isEmpty())
            throw new RuntimeException(MessageConstant.QUERY_SETMEALLIST_FAIL);


        return new Result(true, MessageConstant.QUERY_SETMEALLIST_SUCCESS, setmealList);
    }

    /**
     * 查询套餐包含的检查组和检查组包含的检查项
     *
     * @param setmealId
     * @return
     */
    @Override
    public Result findById(Integer setmealId) {
        Setmeal setmeal = setmealDao.findById(setmealId);

        if (setmeal == null)
            throw new RuntimeException("获取套餐详情失败");

        return new Result(true, "获取套餐详情成功", setmeal);
    }


    private void createSetMealDetailHtml(Integer setmealId) throws Exception {
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("setmeal_detail.ftl");

        Result result = findById(setmealId);
        Setmeal setmeal = (Setmeal) result.getData();
        Map<String, Setmeal> map = new HashMap<>();

        map.put("setmeal", setmeal);
        Writer out = new FileWriter(outPutPath + "setmeal_detail_" + setmealId + ".html");
        template.process(map, out);

        out.close();

    }


    @Override
    public List<Map<String, Object>> findSetmealCount() {
        List<Map<String, Object>> list = setmealDao.findSetmealCount();
        if (list.isEmpty())
            throw new RuntimeException(MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);

        return list;
    }
}
